package message;

import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;

import message.reflect.HandlerMapper;
import message.util.Step;

public class ObjectMessageParserSupplier implements MessageParserSupplier {

	private HandlerMapper mapper;
	public ObjectMessageParserSupplier(HandlerMapper mapper) {
		this.mapper = mapper;
	}
	
	@Override
	public MessageParser parse(Object obj) {
		return new AbstractMessageParser(obj) {
			private Step step = new Step();
//			private int code = ClassReflect.getCode(mapper, object.getClass());
			private long code;
			{
//				System.out.println(object.getClass());
				if(object == null) code = 0;
				else code = mapper.getTypeCode(object.getClass());
			}
			private MessageParser parser;
			@Override
			public boolean write(ByteBuffer byteBuffer) {
				if(step.is(0)) {
					try {
						byteBuffer.putLong(code);		
						if(code == 0) return true;
					} catch (BufferOverflowException e) {
						return false;
					}
					try {
//						System.out.println(mapper.getType(code));
						parser = mapper.getParserSupplier(Class.forName(mapper.getType(code))).parse(object);
//						System.out.println(parser);
					} catch (ClassNotFoundException e) {
						e.printStackTrace();
					}
					step.done();
				}
				if(step.is(1)) {
					if(!(parser.write(byteBuffer))) return false;
					step.done();
				}
				return true;
			}
		};
	}

}
